package controller

import (
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gin-gonic/gin"
	"kf/constant"
	"kf/models/dao"
	"kf/models/entity"
	"kf/utils/R"
	"net/http"
	"strconv"
)

type SysUserController struct {
	SysUserDao      *dao.SysUserDao
	SysRoleDao      *dao.SysRoleDao
	SysUserRolesDao *dao.SysUserRolesDao
	SysRoleMenuDao  *dao.SysRoleMenuDao
}

// 获取登陆人员的信息
func (sysUserController *SysUserController) MeV1(c *gin.Context) {
	//获取用户信息
	value, exists := c.Get(constant.UserInfo)
	if !exists {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户信息不存在",
		})
		return
	}
	//用户信息
	userinfo := value.(map[string]any)
	userId := userinfo[constant.UserId]
	toInt, err := convertor.ToInt(userId)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户信息不存在",
		})
		return
	}
	userRoles := sysUserController.SysUserRolesDao.FindRolesByUserId(uint64(toInt))
	//角色
	var roles []string
	//权限
	var perms []string
	for _, userRole := range userRoles {
		form, err := sysUserController.SysRoleDao.GetRoleForm(int64(userRole.RoleId))
		if err != nil {
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "用户信息不存在",
			})
			return
		}
		roles = append(roles, form.Code)
		list := sysUserController.SysRoleMenuDao.GetRolePermsList(form.Code)
		for _, bo := range list {
			perms = append(perms, bo.Perms...)
		}
	}
	perms = slice.Unique(perms)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "验证成功,正在跳转",
		"data": gin.H{
			"avatar":   userinfo[constant.Avatar],
			"nickname": userinfo[constant.NikeName],
			"perms":    perms,
			"roles":    roles,
			"userId":   userId,
			"username": userinfo[constant.UserName],
		},
	})
}

func (sysUserController *SysUserController) Page(c *gin.Context) {
	var pageQuery entity.SysUserPageQuery
	err := c.ShouldBindQuery(&pageQuery)
	if err != nil {
		c.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	users, err := sysUserController.SysUserDao.ListPagedUsers(pageQuery)
	if err != nil {
		c.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(users))
}

// 查询客服id和名称
func (sysUserController *SysUserController) Option(c *gin.Context) {
	users, err := sysUserController.SysUserDao.Option()
	if err != nil {
		c.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(users))
}

func (sysUserController *SysUserController) UpdatePassword(c *gin.Context) {
	// 使用Param方法获取URL中的变量值
	userIdStr := c.Param("userId")
	// 尝试将字符串转换为整数
	userId, err := strconv.Atoi(userIdStr)
	if err != nil {
		// 如果转换失败，返回错误响应
		c.JSON(http.StatusInternalServerError, "Invalid ID")
		return
	}

	password := c.Query("password")
	result := sysUserController.SysUserDao.UpdatePassword(userId, password)
	c.JSON(http.StatusOK, R.ReturnSuccess(result))
}

// 根据id获取用户信息
func (sysUserController *SysUserController) GetUserForm(c *gin.Context) {
	userIdStr := c.Param("userId")
	// 尝试将字符串转换为整数
	userId, err := convertor.ToInt(userIdStr)
	if err != nil {
		// 如果转换失败，返回错误响应
		c.JSON(http.StatusInternalServerError, "Invalid ID")
		return
	}
	userForm, err := sysUserController.SysUserDao.GetUserForm(userId)
	if err != nil {
		// 如果转换失败，返回错误响应
		c.JSON(http.StatusInternalServerError, "查询失败")
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(userForm))
}

// 新建用户
func (sysUserController *SysUserController) SaveUser(context *gin.Context) {
	var userForm entity.UserForm
	err := context.ShouldBindJSON(&userForm)
	if err != nil {
		context.JSON(http.StatusInternalServerError, "新增用户失败")
		return
	}
	result, err := sysUserController.SysUserDao.SaveUser(userForm)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}

// 修改用户
func (sysUserController *SysUserController) UpdateUser(context *gin.Context) {
	var userForm entity.UserForm
	err := context.ShouldBindJSON(&userForm)
	if err != nil {
		context.JSON(http.StatusInternalServerError, "修改用户失败")
		return
	}
	result, err := sysUserController.SysUserDao.UpdateUser(userForm)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}

// 删除用户
func (sysUserController *SysUserController) DeleteUsers(context *gin.Context) {
	idStr := context.Param("ids")
	b, err := sysUserController.SysUserDao.DeleteUsers(idStr)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(b))
}
